package com.ajun.task;

import cn.hutool.core.collection.CollUtil;
import com.ajun.entity.Order;
import com.ajun.entity.OrderMessage;
import com.ajun.mapper.OrderMapper;
import com.ajun.mapper.OrderMessageMapper;
import com.ajun.producer.OrderProducer;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息发送失败定时重试
 *
 * @author AJun
 * @date 2021-07-15
 */
@Slf4j
@Service
public class OrderMsgRetryTask {

    @Resource
    private OrderMessageMapper orderMessageMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderProducer orderProducer;

    @Scheduled(cron = "30/30 * * * * ?")
    public void msgRetrySend() {
        log.info("定时扫描 order_message 冗余表,重新发送发送失败的消息");
        List<OrderMessage> orderMessageList = orderMessageMapper.selectList(
            Wrappers.<OrderMessage>lambdaQuery()
                .eq(OrderMessage::getStatus, -1)
        );
        List<Order> failedOrderList = new ArrayList<>();
        for (OrderMessage orderMessage : orderMessageList) {
            failedOrderList = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .eq(Order::getOrderId, orderMessage.getOrderId())
            );
        }
        if (CollUtil.isNotEmpty(failedOrderList)) {
            failedOrderList.forEach(order -> orderProducer.sendOrderMsg(order));
        }
    }
}
